const Router = require('koa-router')
const router = Router()
const bcrypt = require('bcryptjs')
const tools = require('../../config/tools')
const gravatar = require('gravatar')
const jwt = require('jsonwebtoken')
const keys = require('../../config/keys')

// 引入
const User = require('../../models/User')

/**
 * @route GET api/users/test
 */
router.get('/test', async ctx => {
  ctx.status = 200
  ctx.body = {
    msg: 'user works'
  }
})

/**
 * @route POST api/users/register
 */
router.post('/register', async ctx => {
  // 存到数据库
  const findResult = await User.find({
    email: ctx.request.body.email
  })
  if (findResult.length > 0) {
    ctx.status = 500
    ctx.body = {
      email: '邮箱已被占用'
    }
  } else {
    const avatar = gravatar.url(ctx.request.body.email, {
      s: '200',
      r: 'pg',
      d: 'mm'
    })

    const newUser = new User({
      name: ctx.request.body.name,
      email: ctx.request.body.email,
      avatar,
      password: tools.enbcrypt(ctx.request.body.password)
    })
    console.log(newUser.password)

    // 存到数据库
    await newUser
      .save()
      .then(user => {
        ctx.body = user
      })
      .catch(err => {
        console.log(err)
      })
  }
})

/**
 * @route POST api/users/login
 */
router.post('/login', async ctx => {
  // 查询
  const findResult = await User.find({ email: ctx.request.body.email })
  const password = ctx.request.body.password
  const user = findResult[0]
  if (findResult.length == 0) {
    ctx.status = 404
    ctx.body = { email: '邮箱不存在' }
  } else {
    // 验证密码
    const result = await bcrypt.compareSync(password, user.password) // true

    // 验证通过
    if (result) {
      // 返回token
      const payload = { id: user.id, name: user.name, avatar: user.avatar }
      const token = jwt.sign(payload, keys.secretOrKey, { expiresIn: 3600 })

      ctx.status = 200
      ctx.body = { success: '登陆成功', token: 'Bearer ' + token }
    } else {
      ctx.status = 400
      ctx.body = { password: '密码错误' }
    }
  }
})

/**
 * @route GET api/users/current
 */
router.get('/current', 'token验证', async ctx => {
  ctx.body = { success: true }
})

module.exports = router.routes()
